import {
  reqCode,
  reqUserInfo,
  reqUserLogin,
  reqUserLogout,
  reqUserRegister,
} from "@/api";
import { getUserToken, removeToken, setToken } from "@/utils/token";

// use仓库
const state = {
  code: "",
  //token
  token: getUserToken(),
  //用户昵称
  nickname: "",
};
const mutations = {
  GETCODE(state, payload) {
    state.code = payload;
  },
  USERLOGIN(state, payload) {
    state.token = payload;
  },
  GETUSERINFO(state, payload) {
    state.nickname = payload;
  },
  REMOVEUSER(state) {
    state.token = "";
    state.nickname = "";
    removeToken();
  },
};
const actions = {
  async getCode({ commit, state, dispatch, getters }, phone) {
    let result = await reqCode(phone);
    if (result.code == 200) {
      commit("GETCODE", result.data);
      return "ok";
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
  async userRegister({ commit, dispatch, state, getters }, data) {
    let result = await reqUserRegister(data);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
  async userLogin({ commit, dispatch, state, getters }, data) {
    let result = await reqUserLogin(data);
    if ((result.code = 200)) {
      commit("USERLOGIN", result.data.token);
      setToken(result.data.token);
      return "ok";
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
  //获取用户信息
  async getUserInfo({ commit, dispatch, state, getters }) {
    let { code, message, data } = await reqUserInfo();
    if (code !== 200) throw new Error(message);
    commit("GETUSERINFO", data.nickName);
  },
  //退出登录
  async userLogout({ commit, state, dispatch, getters }) {
    let result = await reqUserLogout();
    if (result.code == 200) {
      commit("REMOVEUSER");
      return "ok";
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
};
const getters = {};

// 暴漏
export default {
  state,
  mutations,
  actions,
  getters,
};
